﻿using System.Collections;
using System.Collections.Generic;

namespace Gmantis.Controls.DataGrid
{
    internal abstract class DataGridViewCollection<T1, T2> : IEnumerable<T2>, IEnumerable where T2 : IDataGridViewItem
    {
        // Fields
        private Dictionary<T1, T2> _items;
        private string TName;

        // Methods
        public DataGridViewCollection(DataGridView view)
        {
            this._items = new Dictionary<T1, T2>();
            this.TName = typeof(T2).Name;
            this.View = view;
        }

        public void Clear()
        {
            foreach (KeyValuePair<T1, T2> pair in this._items)
            {
                pair.Value.FinalizeViewItem();
            }
            this._items.Clear();
        }

        public IEnumerator<T2> GetEnumerator()
        {
            return this._items.Values.GetEnumerator();
        }

        public abstract T2 OnCreatingItem(T1 index);
        public void Remove(T1 key)
        {
            this._items[key].FinalizeViewItem();
            this._items.Remove(key);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public bool TryGetValue(T1 key, out T2 item)
        {
            return this._items.TryGetValue(key, out item);
        }

        // Properties
        public T2 this[T1 key]
        {
            get
            {
                T2 local;
                if (!this._items.TryGetValue(key, out local))
                {
                    local = this.OnCreatingItem(key);
                    this._items[key] = local;
                    local.InitializeViewItem();
                }
                return local;
            }
        }

        protected DataGridView View { get; private set; }
    }
}
